from collections import OrderedDict
from datetime import datetime, timedelta
from time import time
import json

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from django.http import FileResponse

from .serializer import *
from apps import redis_client
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError
from .models import *


class PublistView(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="list")
    def publish_list(self, requests, *args, **kwargs):
        publishs = PublishModel.objects.filter(is_delete=False).all()
        page = MyPageNumberPagination()
        page_usrs = page.paginate_queryset(queryset=publishs, request=requests, view=self)
        gateway_re = PublishListSerializer(instance=page_usrs, many=True)
        return Response(self.__get_paginated_response(page, requests, gateway_re.data))

    def __get_paginated_response(self, page, request, datas):
        a = OrderedDict([
            ('current', int(page.get_page_number(request, page))),
            ('total', int(page.page.paginator.count)),
            ('pageSize', int(page.get_page_size(request))),
            ('data', datas),
            ("code", 200),
        ])
        return a

    @action(detail=False, methods=["GET", ], url_path="tool_list")
    def tool_list(self, requests, *args, **kwargs):
        file_name = self.request.GET.get("file_name")
        product_number = self.request.GET.get("product_number")
        tools = ToolProductModel.objects.filter(is_delete=False)
        if file_name:
            tools = tools.filter(file_name__icontains=file_name)
        if product_number:
            tools = tools.filter(product_number__icontains=product_number)
        tools = tools.values("product_number", "file_name").distinct()
        page = MyPageNumberPagination()
        page_usrs = page.paginate_queryset(queryset=tools, request=requests, view=self)
        gateway_re = ToolSerializer(instance=page_usrs, many=True)
        return Response(self.__get_paginated_response(page, requests, gateway_re.data))

    @action(detail=False, methods=["GET", ], url_path="version_list")
    def version_list(self, requests, *args, **kwargs):
        file_name = self.request.GET.get("file_name")
        product_number = self.request.GET.get("product_number")
        if file_name and product_number:
            tools = ToolProductModel.objects.filter(is_delete=False)
            tools = tools.filter(file_name=file_name)
            tools = tools.filter(product_number=product_number).all()
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=tools, request=requests, view=self)
            gateway_re = VersionSerializer(instance=page_usrs, many=True)
            return Response(self.__get_paginated_response(page, requests, gateway_re.data))
        else:
            raise ValidationError(20001)

    @action(detail=False, methods=["GET", ], url_path="version_down")
    def version_down(self, requests, *args, **kwargs):
        file_path = self.request.GET.get("file_path")
        version = self.request.GET.get("version")
        data = {
            "file_path": file_path,
            "version": version
        }
        serializer = VersionDownSerializer(data=data)
        if serializer.is_valid():
            file_path, has_file = serializer.get_file(serializer.validated_data)
            if has_file:
                try:
                    file_path = settings.VERSION_PATH.format(file_path)
                    file = open(file_path, 'rb')
                    response = FileResponse(file)
                    response['Content-Type'] = 'application/octet-stream'
                    response['Content-Disposition'] = 'attachment;filename="{}"'.format("")
                    return response
                except Exception as e:
                    print(e)
                    raise ValidationError(30001)
            else:
                return Response()
        else:
            raise ValidationError(20001)

    @action(detail=False, methods=["GET", ], url_path="version_remove")
    def version_remove(self, requests, *args, **kwargs):
        file_path = self.request.GET.get("file_path")
        try:
            os.remove(file_path)
        except:
            pass
        return Response({"code": 200, "data": {}})

    @action(detail=False, methods=["GET", ], url_path="publish_detial_list")
    def publish_detial_list(self, requests, *args, **kwargs):
        publish_id = self.request.GET.get("publishid")
        if publish_id:
            publish_details = PublishDetialModel.objects.filter(publish_id=publish_id).all()
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=publish_details, request=requests, view=self)
            gateway_re = PublishDetialListSerializer(instance=page_usrs, many=True)
            return Response(self.__get_paginated_response(page, requests, gateway_re.data))
        else:
            return Response({"code": 200, "data": {}})

    @action(detail=False, methods=["GET", ], url_path="version_search")
    def version_search(self, requests, *args, **kwargs):
        file_name = self.request.GET.get("file_name")
        data = {
            "file_name": file_name
        }
        serializer = VersionDetialSerializer(data=data)
        if serializer.is_valid():
            data = serializer.search(serializer.validated_data)
            if data:
                return Response({"code": 200, "data": data, "current": 1, "pageSize": 20, "success": True, "total": 1})
        else:
            return Response({"code": 200, "data": []})

    @action(detail=False, methods=["POST", ], url_path="create")
    def orderproductcreate(self, requests, *args, **kwargs):
        data = {"items": requests.data}
        serializer = publishCreateSerializer(data=data)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["GET", ], url_path="svnformlist")
    def filelist(self, requests, *args, **kwargs):
        svn_path_tool = SvnPathTool()
        results = svn_path_tool.get_dir_info()
        results = self.__deal_result(results)
        results = self.__option_result(results)
        return Response({
            "code": 200,
            "result": results,
        })

    def __deal_result(self, result):
        first = list(result)[0]
        datas = result.get(first)
        return datas

    def __option_result(self, results):
        data = self.__get_data(results)
        return data

    def __get_data(self, re):
        data = []
        if isinstance(re, dict):
            for key in re:
                value = re.get(key)
                data.append({
                    "value": key,
                    "label": key,
                    "children": self.__get_data(value)
                })
        elif isinstance(re, list):
            for item in re:
                for key in item:
                    value = item.get(key)
                    data.append({
                        "value": key,
                        "label": key,
                        "children": self.__get_data(value)
                    })
        return data

    @action(detail=False, methods=["GET", ], url_path="email_list")
    def email_list(self, requests, *args, **kwargs):
        emails = EmailModel.objects.filter(is_delete=False).all()
        page = MyPageNumberPagination()
        page_usrs = page.paginate_queryset(queryset=emails, request=requests, view=self)
        email_re = EmailListSerializer(instance=page_usrs, many=True)
        return Response(self.__get_paginated_response(page, requests, email_re.data))

    @action(detail=False, methods=["POST"], url_path="email_create")
    def email_create(self, requests, *args, **kwargs):
        data = requests.query_params
        email_name = data.get("email_name")
        data = {
            "email_name": email_name if email_name else None,
        }
        serializer = EmailCreateSerializerList(data=data)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加邮箱成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="email_update")
    def email_update(self, requests, *args, **kwargs):
        user_id = requests.query_params.get("id")
        is_active = requests.query_params.get("is_active")
        is_delete = requests.query_params.get("is_delete")
        data = {
            "id": user_id if user_id else None,
            "is_active": is_active if is_active else None,
            "is_delete": is_delete if is_delete else None,
        }
        serializer = EmailserializerUpdate(data=data)
        if serializer.is_valid():
            serializer.update_user(serializer.validated_data)
            return Response({"code": 200, "msg": "修改成功"})
        else:
            raise ValidationError(20001)


